#include "Window.h"
namespace devii
{
//this-pointer for the window-function
Window * window; 

Window::Window()
{
	window = this;
}

Window::~Window()
{
}

Window::Window( unsigned int width, unsigned int height )
{
	this->width = width;
	this->height = height;
	window = this;
}


LRESULT CALLBACK WndProc( HWND wnd, unsigned int msg, WPARAM wpar, LPARAM lpar )
{
	if( window->onMessage( msg, wpar, lpar ) )
		return 0;
	else
		return DefWindowProc( wnd, msg, wpar, lpar );
}

void Window::init()
{
	width = width;
	height = height;

	WNDCLASS wc;
	
	wc.style 			= CS_HREDRAW | CS_VREDRAW;
	wc.lpfnWndProc 		= WndProc;
	wc.cbClsExtra 		= 0;
	wc.cbWndExtra 		= 0;
	wc.hInstance 		= 0;
	wc.hIcon			= LoadIcon(0, IDI_APPLICATION);
	wc.hCursor			= LoadCursor(0, IDC_ARROW);
	wc.hbrBackground	= (HBRUSH)GetStockObject(WHITE_BRUSH);
	wc.lpszMenuName		= 0;
	wc.lpszClassName 	= 0;
	wc.lpszClassName	= "BasicWndClass";

	if( !RegisterClass(&wc) ){
		MessageBox(0, "Register WNDClass FAILED", 0, 0);
	}

    RECT r;
    r.bottom = height;
    r.top = 0;
    r.left = 0;
    r.right = width;
    AdjustWindowRect( &r, WS_OVERLAPPEDWINDOW, false);

    wnd = CreateWindow("BasicWndClass","devii - triangle",
        WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT,
        CW_USEDEFAULT,
        r.right,
        r.bottom,
        0,
        0,
        0,
        0);

	if(wnd == 0){
		MessageBox(0, "Init window failed", 0 ,0);
	}

	ShowWindow(wnd, true);
	
}

void Window::update()
{
	MSG msg = {0};

	if( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) ){
		TranslateMessage( &msg );
		DispatchMessage( &msg );
	}
}
bool Window::onMessage( unsigned int msg, WPARAM wpar, LPARAM lpar )
{
	float x = LOWORD(lpar);
	float y = HIWORD(lpar);
	switch( msg )
	{
		case WM_KEYDOWN:
			onInput( wpar, DOWN, KEYBOARD, lpar );
			return true;
		break;

		case WM_KEYUP:
			onInput( wpar, UP, KEYBOARD, lpar );
			return true;
		break;
			
		case WM_DESTROY:
			kill();
			return true;
		break;

		case WM_LBUTTONDOWN:
			onInput( wpar, DOWN, MOUSE, lpar );
			return true;
		break;

		case WM_LBUTTONUP:
			onInput( wpar + 1, UP, MOUSE, lpar );
			return true;
		break;

		case WM_RBUTTONDOWN:
			onInput( wpar, DOWN, MOUSE, lpar );
			return true;
		break;

		case WM_RBUTTONUP:
			onInput( wpar + 2, UP, MOUSE, lpar );
			return true;
		break;

		case WM_MOUSEMOVE:
			onMouseMovement( x, y );
			break;
		default:
			return false;
		break;
	}

	return false;
}

void Window::onInput( int key, KeyState state, InputDevice input, LPARAM lpar )
{

}

void Window::onMouseMovement( float x, float y )
{

}

void Window::kill()
{
}

unsigned int Window::getHeight()
{
	return height;
}

unsigned int Window::getWidth()
{
	return width;
}

}